<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Math.signbit()</title>
</head>
<body>
    <h1>Math.signbit()</h1>
    <h2>判断一个数的符号位是否设置</h2>

    <script>
        // 目前的判断方法
        function hasNegativeSign(x) {
            return x === 0 ? 1/x === -Infinity : x < 0;
        }

        // Math.signbit提案的用法
        /*
        Math.signbit(3);     // false
        Math.signbit(-3);    // true
        Math.signbit(0);     // false
        Math.signbit(-0);    // true
        Math.signbit(NaN);   // false
        */

        // 实际应用示例
        // 1. 数值比较
        function compareWithSign(a, b) {
            const signA = hasNegativeSign(a);
            const signB = hasNegativeSign(b);
            
            if (signA !== signB) {
                return signA ? -1 : 1;
            }
            return a - b;
        }

        // 2. 数学计算
        class Vector {
            constructor(x, y) {
                this.x = x;
                this.y = y;
            }

            rotate(angle) {
                const cos = Math.cos(angle);
                const sin = Math.sin(angle);
                return new Vector(
                    this.x * cos - this.y * sin,
                    this.x * sin + this.y * cos
                );
            }

            get direction() {
                return hasNegativeSign(this.x) ? 'left' : 'right';
            }
        }

        // 3. 金融计算
        class MoneyAmount {
            constructor(value) {
                this.value = value;
            }

            toString() {
                const sign = hasNegativeSign(this.value) ? '-' : '';
                return `${sign}$${Math.abs(this.value).toFixed(2)}`;
            }

            isDebit() {
                return hasNegativeSign(this.value);
            }

            isCredit() {
                return !this.isDebit();
            }
        }

        // 使用示例
        const amount1 = new MoneyAmount(100.50);
        const amount2 = new MoneyAmount(-50.25);

        console.log(amount1.toString()); // "$100.50"
        console.log(amount2.toString()); // "-$50.25"
        console.log(amount1.isCredit()); // true
        console.log(amount2.isDebit());  // true
    </script>
</body>
</html> 